package com.lzj.jiangxindaojia.http;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.lzj.jiangxindaojia.utils.LogUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by lizj on 2017/12/4.
 */

public class HttpUtil {
    private OkHttpClient mOkHttpClient;
    public static final MediaType MEDIA_TYPE_MARKDOWN
            = MediaType.parse("text/x-markdown; charset=utf-8");
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private static HttpUtil instance = null;

    public HttpUtil(Context context) {
        initOkHttpClient(context);
    }

    public static HttpUtil getInstance(Context context) {
        if (instance == null) {
        }
        try {
            if (instance == null) {
                instance = new HttpUtil(context);
            }
            return instance;
        } finally {
        }
    }


    private void initOkHttpClient(Context context) {
        File sdcache = context.getExternalCacheDir();
        int cacheSize = 10 * 1024 * 1024;
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
        mOkHttpClient = builder.build();
    }

    /**
     * get异步请求
     */
    public  void getAsynHttp(String url, Map<String, Object> map, final Context context, final HttpCallBack callback, final String action) {


        StringBuffer sb =  new StringBuffer();
        /**
         * 创建请求的参数body
         */
        FormBody.Builder builder = new FormBody.Builder();
        /**
         * 遍历key
         */
        if (null != map) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                LogUtils.log("requestParams=====> key= " + entry.getKey() + ", Value = "
                        + entry.getValue());
                builder.add(entry.getKey(), entry.getValue().toString());
                sb.append("?");
                sb.append("&"+entry.getKey()+"="+entry.getValue());
                LogUtils.log("sb "+sb.toString());
            }
        }
        RequestBody body = builder.build();
        Request.Builder requestBuilder = new Request.Builder().url(url);
        requestBuilder.method("GET", body);
        Request request = requestBuilder.build();

//        //1.okhttpClient对象
//        OkHttpClient okHttpClient = new OkHttpClient();
//        //2构造Request,
//        //builder.get()代表的是get请求，url方法里面放的参数是一个网络地址
//        Request.Builder builder = new Request.Builder();
//        Request request = builder.get().url("http://www.baidu.com/").build();


//        Request.Builder requestBuilder = new Request.Builder().url("http://www.baidu.com");
//        requestBuilder.method("GET", null);
//        Request request = requestBuilder.build();


        Call mcall = mOkHttpClient.newCall(request);
        mcall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String msg = e.getMessage();
                e.printStackTrace();
                LogUtils.log("msg " + msg);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                LogUtils.log("requestResult=====> " + result);
                if (response.isSuccessful()) {
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            callback.onSuccess(result, action);
                        }
                    });
                } else {
                    String msg = response.message();
                    LogUtils.log("msg " + msg);
                }
//                if (null != response.cacheResponse()) {
//                    String str = response.cacheResponse().toString();
//                    Log.i("wangshu", "cache---" + str);
//                } else {
//                    response.body().string();
//                    String str = response.networkResponse().toString();
//                    Log.i("wangshu", "network---" + str);
//                }
//                ((Activity) context).runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(context, "请求成功", Toast.LENGTH_SHORT).show();
//                    }
//                });
            }
        });
    }

    /**
     * post异步请求
     */
    public void postAsynHttp(String url, Map<String, Object> map, final Context context, final HttpCallBack callback, final String action) {
        LogUtils.log("===========================================================================");
        LogUtils.log("requestUrl=====> " + url);
        /**
         * 创建请求的参数body
         */
        FormBody.Builder builder = new FormBody.Builder();
        /**
         * 遍历key
         */
        if (null != map) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                LogUtils.log("requestParams=====> key= " + entry.getKey() + ", Value = "
                        + entry.getValue());
                builder.add(entry.getKey(), entry.getValue().toString());
            }
        }
        RequestBody body = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String msg = e.getMessage();
                e.printStackTrace();
                LogUtils.log("msg " + msg);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                LogUtils.log("requestResult=====> " + result);
                if (response.isSuccessful()) {
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            callback.onSuccess(result, action);
                        }
                    });
                } else {
                    String msg = response.message();
                    LogUtils.log("msg " + msg);
                }
            }
        });
    }

    /**
     * 异步上传文件
     */
    private void postAsynFile() {
        File file = new File("/sdcard/wangshu.txt");
        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i("wangshu", response.body().string());
            }
        });
    }


    /**
     * 异步下载文件
     */
    private void downAsynFile() {
        String url = "http://img.my.csdn.net/uploads/201603/26/1458988468_5804.jpg";
        Request request = new Request.Builder().url(url).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) {
                InputStream inputStream = response.body().byteStream();
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(new File("/sdcard/wangshu.jpg"));
                    byte[] buffer = new byte[2048];
                    int len = 0;
                    while ((len = inputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, len);
                    }
                    fileOutputStream.flush();
                } catch (IOException e) {
                    Log.i("wangshu", "IOException");
                    e.printStackTrace();
                }

                Log.d("wangshu", "文件下载成功");
            }
        });
    }

    private void sendMultipart() {
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("title", "wangshu")
                .addFormDataPart("image", "wangshu.jpg",
                        RequestBody.create(MEDIA_TYPE_PNG, new File("/sdcard/wangshu.jpg")))
                .build();

        Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + "...")
                .url("https://api.imgur.com/3/image")
                .post(requestBody)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i("wangshu", response.body().string());
            }
        });
    }

}
